package com.sita.linboard.journey;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.CardView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.overlay.WalkRouteOverlay;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkPath;
import com.amap.api.services.route.WalkRouteResult;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMCmdMessageBody;
import com.hyphenate.chat.EMMessage;
import com.sita.linboard.MainMessage.MainActivity;
import com.sita.linboard.R;
import com.sita.linboard.base.BaseActivity;
import com.sita.linboard.base.BaseApplication;
import com.sita.linboard.calllist.UtilsBean;
import com.sita.linboard.calllist.VehicleListActivity;
import com.sita.linboard.http.RestClient;
import com.sita.linboard.receipt.ReceiptActivity;
import com.sita.linboard.utils.Constants;
import com.sita.linboard.utils.LogUtils;
import com.sita.linboard.utils.SpUtils;
import com.sita.linboard.utils.ToastUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
import retrofit.mime.TypedFile;
import retrofit.mime.TypedString;

/**
 * Created by Jason on 2016/8/24.
 */
public class OrderReceivActivity extends BaseActivity implements LocationSource
        , AMapLocationListener, View.OnClickListener, AMap.OnInfoWindowClickListener,
        AMap.InfoWindowAdapter, RouteSearch.OnRouteSearchListener {
    private static double driver_lng, driver_lat;
    private static int INDEX;
    private static boolean TimeStart = true;
    private static boolean FirstRoute = true;
    private static int FirstSet = 1;
    private final int ROUTE_TYPE_BUS = 1;
    private final int ROUTE_TYPE_DRIVE = 2;
    private final int ROUTE_TYPE_WALK = 3;
    RouteSearch.FromAndTo fromAndTo;
    private String TAG = getClass().getSimpleName();
    private ImageView myLocation;
    private Marker myLocation_marker;
    private Marker startMarker;
    private Marker endMarker;
    private Button received_btn;
    private MapView baseMap;
    private AMap aMap;
    private ProgressDialog dialog;
    private OnLocationChangedListener mListener;
    private AMapLocationClient mapLocationClient;
    private AMapLocationClientOption mapLocationClientOption;
    private WalkRouteOverlay walkRouteOverlay;
    private UiSettings uiSettings;
    private CardView userinfo;
    private TextView headTitle, user_start, user_end;
    private UtilsBean beanData;
    private String nowState;
    private EMMessageListener messageListener;
    private Button callUser;
    private File zipFile = null;
    private File file = null;
    private List<LocMessage> locMessages = new ArrayList<>();
    //    private LocMessage locMessage = new LocMessage();
    //----------------------------------------------------路线规划
    private RouteSearch mRouteSearch;
    private LatLonPoint mStartPotion;//司机的位置
    private LatLonPoint mEndPotion;  //结束的位置   1：起点 2:终点
    private LatLonPoint mNewEndPotion;  //终点位置
    private WalkRouteResult mWalkRouteResult;
    private int PERMISSON_REQUESTCODE = 0;
    private UserLocation data;
    //----------------------------------------------------handler来接收消息刷新UI
    private MyHandler handler = new MyHandler(this);

    public static void OrderIntent(Context context, UtilsBean bean, String state) {
        Intent intent = new Intent(context, OrderReceivActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("vehicleList", bean);
        bundle.putString("state", state);
        intent.putExtras(bundle);
        context.startActivity(intent);
    }

    public static String sHA1(Context context) {
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), PackageManager.GET_SIGNATURES);
            byte[] cert = info.signatures[0].toByteArray();
            MessageDigest md = MessageDigest.getInstance("SHA1");
            byte[] publicKey = md.digest(cert);
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < publicKey.length; i++) {
                String appendString = Integer.toHexString(0xFF & publicKey[i])
                        .toUpperCase(Locale.US);
                if (appendString.length() == 1)
                    hexString.append("0");
                hexString.append(appendString);
                hexString.append(":");
            }
            String result = hexString.toString();
            return result.substring(0, result.length() - 1);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public View getInfoWindow(Marker marker) {
        return null;
    }

    @Override
    public View getInfoContents(Marker marker) {
        return null;
    }

    @Override
    public void onInfoWindowClick(Marker marker) {
    }

    @Override
    public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {
    }

    @Override
    public void onDriveRouteSearched(DriveRouteResult driveRouteResult, int i) {
    }

    //-------------------------------------------------步行规划
    @Override
    public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) {
        Log.e(TAG, i + "返回码");
        dialog.dismiss();
        if (i == 1000) {

            if (walkRouteResult != null && walkRouteResult.getPaths() != null) {
                if (walkRouteResult.getPaths().size() > 0) {
                    mWalkRouteResult = walkRouteResult;
                    final WalkPath walkPath = mWalkRouteResult.getPaths().get(0);
                    walkRouteOverlay = new WalkRouteOverlay(
                            this, aMap, walkPath,
                            mWalkRouteResult.getStartPos(),
                            mWalkRouteResult.getTargetPos());
                    walkRouteOverlay.removeFromMap();
                    walkRouteOverlay.addToMap();
                    walkRouteOverlay.setNodeIconVisibility(false);
                    walkRouteOverlay.zoomToSpan();//让所有的Marker显示到屏幕上
                } else if (walkRouteResult != null && walkRouteResult.getPaths() == null) {

                    ToastUtils.show("路线规划失败,请及时联系用户", 3);
                }
            } else {
                ToastUtils.show("路线规划失败,请及时联系用户", 3);
            }
        } else {
            ToastUtils.show("路线规划失败,请及时联系用户", 3);
        }

    }

    @Override
    protected void onStart() {
        super.onStart();
        FirstSet = 1;
        if (nowState.equals("2")) {
            FirstSet = 2;
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //不管监听与否，都设为不监听状态
        Constants.isReady = false;
        if (!BaseApplication.isNetworkAvailable() && BaseApplication.isGpsEnabled()) {
            ToastUtils.show("请开启网络和定位！", 5);
        }
        nowState = getIntent().getStringExtra("state");
        beanData = (UtilsBean) getIntent().getSerializableExtra("vehicleList");
        INDEX = 0;
        getMessageFromHX();
        baseMap = (MapView) findViewById(R.id.location_map);
        baseMap.onCreate(savedInstanceState);
        //接收订单的信息
        initMap();
        markDepartureOnMap();
        initDatas();
    }

    private void initDatas() {
        user_start.setText(getString(R.string.start_location, beanData.getDeparture_addr()));
        user_end.setText(getString(R.string.end_location, beanData.getArrival_addr()));
        callUser.setOnClickListener(this);
        headTitle.setText("去接乘客");
        received_btn.setText("接到乘客");
        received_btn.setOnClickListener(this);
        myLocation.setOnClickListener(this);

        if (nowState.equals("2")) {
            startTravel();
        }
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        received_btn = (Button) findViewById(R.id.received);
        userinfo = (CardView) findViewById(R.id.user_message);
        headTitle = (TextView) findViewById(R.id.head_title);
        headTitle.setVisibility(View.VISIBLE);
        user_start = (TextView) findViewById(R.id.user_start_location);
        user_end = (TextView) findViewById(R.id.user_end_location);
        callUser = (Button) findViewById(R.id.call_user_img);
        myLocation = (ImageView) findViewById(R.id.my_location);
    }

    //----------------------------- 给开始地点标记
    private void markDepartureOnMap() {

        LatLng latLng = new LatLng(beanData.getDeparture_lat(), beanData.getDeparture_lng());
        drawStartMyMarker(latLng);

    }

    //------------------------------------------------------------------------------- 终点标记
    private void markArrivalOnMap() {
        LatLng latLng = new LatLng(beanData.getArrival_lat(), beanData.getArrival_lng());
        drawEndMyMarker(latLng);
    }

    private void initView() {

    }

    //--------------------------------------------------------------------------------- 环信消息接听
    private void getMessageFromHX() {
        messageListener = new EMMessageListener() {
            @Override
            public void onMessageReceived(List<EMMessage> list) {
                LogUtils.d(TAG, "收到透传消息1");
            }

            @Override
            public void onCmdMessageReceived(List<EMMessage> list) {
                //乘客位置透传
                LogUtils.d(TAG, "收到透传消息1");
                for (EMMessage message : list) {
                    EMCmdMessageBody body = (EMCmdMessageBody) message.getBody();
                    final String action = body.action();
                    if (!TextUtils.isEmpty(action)) {
                        Log.e("Tag", action);
                        Message locationMsg = new Message();
                        switch (action) {
                            //===================================乘客位置信息透传
                            case "CURRENTLOC":
                                String lng = message.getStringAttribute("lng", "");
                                String lat = message.getStringAttribute("lat", "");
                                UserLocation location = new UserLocation();
                                location.setStartLocation(lng);
                                location.setEndLocation(lat);
                                locationMsg.what = 1;
                                locationMsg.obj = location;
                                LogUtils.d(TAG, "收到透传消息");
                                break;
//==============================================================================取消订单透传
                            case "CANCELORDER":
                                locationMsg.what = 2;
                                Constants.OrderState = false;
                                break;
                        }
                        //发送到主线程   刷新UI
                        handler.sendMessage(locationMsg);
                    }
                }
            }

            @Override
            public void onMessageReadAckReceived(List<EMMessage> list) {
            }

            @Override
            public void onMessageDeliveryAckReceived(List<EMMessage> list) {
            }

            @Override
            public void onMessageChanged(EMMessage emMessage, Object o) {
            }
        };

    }

    //==============================================================================取消订单Dialog
    private void showCalcelOrderDialog() {

        LayoutInflater inflater = getLayoutInflater();
        View view = inflater.inflate(R.layout.cancelldialog, null);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(view);
        Button back_orderList_Bt = (Button) view.findViewById(R.id.determine);
        back_orderList_Bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                VehicleListActivity.VehicleListIntent(OrderReceivActivity.this);
                finish();
            }
        });
        builder.setCancelable(false);
        builder.create();
        builder.show();

    }

    @Override
    protected void initData() {

    }
//----------------------------- 初始化Map

    @Override
    protected int getId() {
        return R.layout.activity_orderreceiv;
    }
    //----------------------------- 跳转页面

    private void initMap() {

        if (aMap == null) {
            aMap = baseMap.getMap();
            aMap.setLocationSource(this);// 设置定位监听
            aMap.getUiSettings().setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
            aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
            // 设置定位的类型为定位模式 ，可以由定位、跟随或地图根据面向方向旋转几种
            aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);

            uiSettings = aMap.getUiSettings();
        }
        //设置定位图片
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        //司机位置
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.mipmap.driver_location_icon));
        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));// 设置圆形的边框颜色  
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));// 设置圆形的填充颜色  
        aMap.setMyLocationStyle(myLocationStyle);
        uiSettings.setScaleControlsEnabled(false);
        uiSettings.setZoomControlsEnabled(false);
        aMap.setOnInfoWindowClickListener(this);
        aMap.setInfoWindowAdapter(this);
        mRouteSearch = new RouteSearch(this);
        mRouteSearch.setRouteSearchListener(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        baseMap.onPause();
        aMap.removecache();
        TimeStart = false;
        EMClient.getInstance().chatManager().removeMessageListener(messageListener);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        TimeStart = false;
        if (mapLocationClient != null) {
            mapLocationClient.onDestroy();
            mapLocationClient.unRegisterLocationListener(this);
        }
        EMClient.getInstance().chatManager().removeMessageListener(messageListener);
        baseMap.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        EMClient.getInstance().chatManager().addMessageListener(messageListener);
        baseMap.onResume();
        FirstRoute = true;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        baseMap.onSaveInstanceState(outState);
    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
        if (mapLocationClient == null) {
            mapLocationClient = new AMapLocationClient(this);
            mapLocationClientOption = new AMapLocationClientOption();
            //设置定位监听
            mapLocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mapLocationClientOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mapLocationClientOption.setInterval(5000);
            mapLocationClient.setLocationOption(mapLocationClientOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mapLocationClient.startLocation();
        }
    }


    //---------------------------------------------------------- LocationSource CallBack 激活定位

    @Override
    public void deactivate() {
        mListener = null;
        if (mapLocationClient != null) {
            mapLocationClient.stopLocation();
            mapLocationClient.onDestroy();
        }
        mapLocationClient = null;

    }

    //------------------------------------------------------------------------------------- 定位回调
    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        driver_lng = aMapLocation.getLongitude();
        driver_lat = aMapLocation.getLatitude();

        if (driver_lat != 0.0 && driver_lng != 0.0) {
            LocMessage locMessage = new LocMessage();
            locMessage.setLng(driver_lng);
            locMessage.setLat(driver_lat);
            locMessage.setTime(aMapLocation.getTime());
            locMessages.add(locMessage);
        }


        if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {
            mListener.onLocationChanged(aMapLocation);//显示定位位置
            if (FirstRoute == true) {
                dialog = ProgressDialog.show(OrderReceivActivity.this, null, "路线规划中...");
                mStartPotion = new LatLonPoint(driver_lat, driver_lng);
                searchRouteResult(ROUTE_TYPE_WALK, RouteSearch.WalkDefault);
            }
            FirstRoute = false;

            LatLng latLng = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
            LogUtils.d(aMapLocation.getLatitude() + "" + aMapLocation.getLongitude());
            if (TimeStart = true) {

                EMMessage cmdMsg = EMMessage.createSendMessage(EMMessage.Type.CMD);
                String action = "CURRENTLOC";
                EMCmdMessageBody cmdBody = new EMCmdMessageBody(action);//
                cmdMsg.setReceipt(String.valueOf(beanData.getCustomer_id()));
                cmdMsg.setAttribute("action", "CURRENTLOC");
                cmdMsg.setAttribute("trip_id", SpUtils.getString("trip_id", null, BaseApplication.getContext()));
                cmdMsg.setAttribute("lng", String.valueOf(aMapLocation.getLongitude()));
                cmdMsg.setAttribute("lat", String.valueOf(aMapLocation.getLatitude()));
                cmdMsg.setAttribute("senderID", SpUtils.getString("AccoundID", null, BaseApplication.getContext()));  //环信id
                Log.e(TAG, SpUtils.getString("AccoundID", null, BaseApplication.getContext()));
                cmdMsg.addBody(cmdBody);
                EMClient.getInstance().chatManager().sendMessage(cmdMsg);
                LogUtils.d(TAG, "发送透传消息" + aMapLocation.getLongitude() + "自己的位置" + aMapLocation.getLatitude());
                cmdMsg.setMessageStatusCallback(new EMCallBack() {
                    @Override
                    public void onSuccess() {
                        Log.d("VehicleList", "send share location success");
                    }

                    @Override
                    public void onError(int i, String s) {
                    }

                    @Override
                    public void onProgress(int i, String s) {

                    }
                });
            }
        } else {

        }
    }

    //------------------------------------------------------------------------------------- 乘客位置
    public void drawPersonMyMarker(LatLng latLng) {
        if (myLocation_marker == null) {
            //定位自己的位置
            Bitmap locationMe = BitmapFactory.decodeResource(
                    this.getResources(), R.mipmap.person_icon);
            BitmapDescriptor icon = BitmapDescriptorFactory.fromBitmap(locationMe);
            myLocation_marker = aMap.addMarker(new MarkerOptions().draggable(false).icon(icon)
                    .position(latLng).setFlat(true));
        } else {
            //设置marker 的经纬度位置。
            myLocation_marker.setPosition(latLng);
        }
    }

    public void drawStartMyMarker(LatLng latLng) {

        //注意参数位置，小心传反了
        if (startMarker == null) {
            //定位自己的位置
            Bitmap locationMe = BitmapFactory.decodeResource(
                    this.getResources(), R.mipmap.start_location);
            BitmapDescriptor icon = BitmapDescriptorFactory.fromBitmap(locationMe);
            startMarker = aMap.addMarker(new MarkerOptions().draggable(false).icon(icon)
                    .position(latLng).setFlat(true));
        } else {
            //设置marker 的经纬度位置。
            startMarker.setPosition(latLng);
        }
        if (FirstSet == 1) {
            mEndPotion = new LatLonPoint(latLng.latitude, latLng.longitude);
        }
    }

    //----------------------------- 开始地点

    //------------------------------------------------------------------------------------ 终点标记
    public void drawEndMyMarker(LatLng latLng) {

        if (endMarker == null) {
            //定位自己的位置
            Bitmap locationMe = BitmapFactory.decodeResource(
                    this.getResources(), R.mipmap.end_location);

            BitmapDescriptor icon = BitmapDescriptorFactory.fromBitmap(locationMe);
            endMarker = aMap.addMarker(new MarkerOptions().draggable(false).icon(icon)
                    .position(latLng).setFlat(true));
        } else {
            //设置marker 的经纬度位置。
            endMarker.setPosition(latLng);
        }
        if (FirstSet == 2) {
            mNewEndPotion = new LatLonPoint(latLng.latitude, latLng.longitude);
        }
    }

    //---------------------------------------------------------------------------在屏蔽系统back键
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return false;
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        return false;
    }

    private void showDialog() {
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setMessage("订单取消")
                .setCancelable(false)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        VehicleListActivity.VehicleListIntent(OrderReceivActivity.this);
                        finish();
                    }
                }).show();
    }


//---------------------------------------------------------------------------------- 订单取消

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.call_user_img:
                BaseActivity.callToUser(this);
                break;
            case R.id.received:
                if (INDEX == 0) {
                    //----------------------------------------------------------------------行程开始
                    if (walkRouteOverlay != null) {
                        walkRouteOverlay.removeFromMap();
                    }
                    if (myLocation_marker != null && messageListener != null) {
                        //   EMClient.getInstance().chatManager().removeMessageListener(messageListener);
                        myLocation_marker.remove();

                    }
                    startTravel();
                    FirstRoute = true;
                    return;

                } else if (INDEX == 1) {

                    //TODO 行程完毕，请求付款
                    //--------------------------------------------------------------发送位置信息zip文件给service
                    // locMessages
                    //参数1：路径
                    //参数2：文件名
                    handler.removeMessages(1);
                    handler.removeMessages(2);
                    file = new File(Environment.getExternalStorageDirectory(), beanData.getTrip_id() + ".json");
                    FileOutputStream out = null;
                    try {
                        out = new FileOutputStream(file);

                        if (!file.exists()) {
                            file.createNewFile();
                        }
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    String title = "{" + "\"points\":" + "[";
                    try {
                        out.write(title.getBytes());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    String separator = "";
                    for (LocMessage lcm : locMessages) {
                        try {
                            out.write(separator.getBytes());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        //给服务器的格式
                        String MyRoute = "{" + " \"longitude\":" + lcm.getLng() + "," +
                                "\"latitude\": " + lcm.getLat() + "," +
                                "\"time\": " + lcm.getTime() +
                                "}";
                        try {
                            out.write(MyRoute.getBytes());
                            separator = ",";
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    }
                    String end = "]" + "}";
                    try {
                        out.write(end.getBytes());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    try {
                        out.flush();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    if (out != null) {
                        try {
                            out.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
                zipFile = new File(Environment.getExternalStorageDirectory(), beanData.getTrip_id() + ".zip");
                try {
                    if (!zipFile.exists()) {
                        zipFile.createNewFile();
                    }
                    com.sita.linboard.utils.ZipUtils.zipFile(file, zipFile);


                } catch (IOException e) {
                    e.printStackTrace();
                }


                TypedFile routeFile = (zipFile.equals("")) ? null : new TypedFile("zip", zipFile);
                RouteHeadParams params = new RouteHeadParams();
                params.trip_id = beanData.getTrip_id();
                String reqStr = RestClient.getGson().toJson(params);
                TypedString parmsType = new TypedString(reqStr);

                RestClient.getRestService().postRoute(parmsType, routeFile, new Callback<PostRouteCallBack>() {

                    @Override
                    public void success(PostRouteCallBack postRouteCallBack, Response response) {
                        ReceiptActivity.ReceiptIntent(OrderReceivActivity.this, beanData.getTrip_id(), beanData.getCustomer_id(),
                                beanData.getDeparture_addr(), beanData.getArrival_addr(), postRouteCallBack.getData().getPayment());


                        finish();
                    }

                    @Override
                    public void failure(RetrofitError error) {
                         final AlertDialog.Builder builder = new AlertDialog.Builder(OrderReceivActivity.this);
                        builder.setTitle("订单异常");
                        builder.setMessage("订单异常，乘客已取消行程");
                        builder.setCancelable(false);
                        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                MainActivity.getMainIntent(OrderReceivActivity.this);
                                finish();
                                builder.create();
                            }
                        });
                        builder.create();
                        builder.show();
                    }
                });

                break;
            case R.id.my_location:
                LatLng myPosition = new LatLng(driver_lat, driver_lng);
                //移动视图到某个坐标
                aMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(
                        myPosition,//新的中心点坐标
                        10, //新的缩放级别
                        0, //俯仰角0°~45°（垂直与地图时为0）
                        0  ////偏航角 0~360° (正北方为0)
                )));
                break;

        }
    }

    //-----------------------------------开始行程
    private void startTravel() {
        FirstSet = 2;
        TimeStart = false;
        startMarker.remove();
        markArrivalOnMap();
        userinfo.setVisibility(View.GONE);
        headTitle.setText("行程开始");
        received_btn.setText("到达目的地");
        //TODO  接到乘客以后做的处理
        OrderRequest request = new OrderRequest();
        request.trip_id = beanData.getTrip_id();
        RestClient.getRestService().getUser(request, new Callback<OrderBackBean>() {
            @Override
            public void success(OrderBackBean orderBackBean, Response response) {
            }

            @Override
            public void failure(RetrofitError error) {
                LogUtils.d("接到乘客失败");
            }
        });
        INDEX = 1;
        return;
    }

    private void searchRouteResult(int routeType, int mode) {
        if (mStartPotion == null) {
            ToastUtils.showShort("定位中，稍后再试...");
        }
        if (FirstSet == 1 && mEndPotion != null) {
            fromAndTo = new RouteSearch.FromAndTo(mStartPotion, mEndPotion);
        } else if (FirstSet == 2 && mNewEndPotion != null) {
            fromAndTo = new RouteSearch.FromAndTo(mStartPotion, mNewEndPotion);
        } else {
            aMap.moveCamera(CameraUpdateFactory.zoomTo(16));
        }
        if (routeType == ROUTE_TYPE_WALK) {
            RouteSearch.WalkRouteQuery query = new RouteSearch.WalkRouteQuery(fromAndTo, mode);
            mRouteSearch.calculateWalkRouteAsyn(query);
        }
    }

    static class MyHandler extends Handler {

        WeakReference<OrderReceivActivity> thisActivity;

        MyHandler(OrderReceivActivity activity) {
            thisActivity = new WeakReference<OrderReceivActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            final OrderReceivActivity activity = thisActivity.get();
            switch (msg.what) {
                case 1:
                    UserLocation location = (UserLocation) msg.obj;
                    LatLng latLng = new LatLng(Double.parseDouble(location.getEndLocation()), Double.parseDouble(location.getStartLocation()));
                    activity.drawPersonMyMarker(latLng);
                    break;
                case 2:
                    activity.showCalcelOrderDialog();
                    break;
            }
        }
    }

}
